package com.fangyuan.util;

import com.fangyuan.model.Fangyuan;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.List;

public class DataSource {
    //驱动程序名
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    //URL指向要访问的数据库名mydata
    private static final String URL = "jdbc:mysql://localhost:3306/fangyuan?useUnicode=true&characterEncoding=utf8";
    //MySQL配置时的用户名
    private static final String USER = "root";
    //MySQL配置时的密码
    private static final String PASSWORD = "root";

    public static Connection getConnection(){
        Connection con=null;
        try {
            //加载驱动程序
            Class.forName(DRIVER);
            //1.getConnection()方法，连接MySQL数据库！！
            con = DriverManager.getConnection(URL,USER,PASSWORD);
            if(!con.isClosed())
                System.out.println("Succeeded connecting to the Database!");
        }catch (Exception e){
            //数据库驱动类异常处理
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
        }
        return con;

    }
    public static void execute(List<String> param, Connection connection){
        String sql="insert into fangyuan (" +
                "community," +
                "address," +
                "doorModel," +
                "square," +
                "floor," +
                "theHeight," +
                "theSubway," +
                "toward," +
                "whetherTheWholeRent," +
                "source," +
                "theContact," +
                "contactPhoneNumber) "
                + "values(?,?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement  statement=null;
        try {
              statement = connection.prepareStatement(sql);
            for (int i = 0; i <param.size() ; i++) {
                statement.setString(i+1,param.get(i));
            }
            statement.execute();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try {
                if(statement!=null)
                statement.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
    public static void close(Connection connection){
        if(connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Fangyuan fangyuan = new Fangyuan();
        fangyuan.setCommunity("111");
        Connection connection = DataSource.getConnection();
        DataSource.execute(fangyuan.getParam(),connection);
    }
}
